<?php

namespace common\models;

use backend\utils\AppUtil;
use Faker\Provider\Uuid;
use Yii;

/**
 * This is the model class for table "users_bound".
 *
 * @property string $uuid
 * @property string $users_id
 * @property string $third_user_id
 * @property string $third_user_name
 * @property string $third_school_name
 * @property integer $status
 * @property string $create_time
 * @property string $update_time
 * @property string $create_users_id
 * @property string $update_users_id
 */
class UsersBound extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sys_users_bound';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['uuid', 'users_id', 'third_user_id', 'third_user_name', 'third_school_name'], 'required'],
            [['status'], 'integer'],
            [['create_time', 'update_time'], 'safe'],
            [['uuid', 'users_id', 'create_users_id', 'update_users_id'], 'string', 'max' => 36],
            [['third_user_id', 'third_user_name', 'third_school_name'], 'string', 'max' => 255],
            [['third_user_id'], 'unique', 'filter' => ['status' => 1], 'message' => '当前用户已经完成绑定 请勿多次绑定。'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'uuid' => '主键',
            'users_id' => '用户id',
            'third_user_id' => '第三方平台用户id',
            'third_user_name' => '第三方用户姓名',
            'third_school_name' => '第三方用户学校',
            'status' => '1：正常  2：删除',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'create_users_id' => '创建人',
            'update_users_id' => '修改人',
        ];
    }

    const BIND = '1'; //绑定
    const UNBIND = '2';//解绑

    public static function getUsersIdByThirdUserId($third_user_id)
    {
        $model = self::find()->where(['third_user_id' => $third_user_id, 'status' => 1])->one();
        if ($model) {
            return $model->users_id;
        } else {
            return false;
        }
    }

    public static function getModel($uuid)
    {
        return self::findOne($uuid);
    }

    public static function edit($data, $users_id, $uuid)
    {
        $model = self::getModel($uuid);
        if (!$model) {
            $model = new self();
            $model->uuid = Uuid::uuid();
            $model->status = AppUtil::STATUS_USE;
            $model->create_time = date('Y-m-d H:i:s');
            $model->create_users_id = $users_id;
        }
        $model->update_time = date('Y-m-d H:i:s');
        $model->update_users_id = $users_id;
        foreach ($data as $key => $value) {
            $model->$key = $value;
        }
        $res = $model->save();
        return [$res, $model];
    }

}
